<?php
namespace App\Http\Controllers\Business\Admin\Salesman;

use App\Models\AdminUser;
use App\Models\SalesmanRecharge;
use App\Models\ShopSalesmanDetail;
use App\Models\User;
use App\Models\SalesmanInfo;
use App\Models\SalesmanHistory;
use App\Models\SalesmanOrder;
use App\Models\SalesmanRegister;
use App\Models\SalesmanSet;
use App\Models\City;
use App\Models\SalesmanWithdraw;
use Auth;
use Exception;
use Log;

class UserSalesmanManagement{

    //salesman_set表中
    //有效地推定义
    //validsalesmanruletype值为1表示：新用户通过地推专属二维码下载app，且在24小时内在app完成登录
    //validsalesmanruletype值为2表示：新用户登录app且消费xx笔  ，单笔消费金额需达xx以上

    //个人地推结算
    //accounttype值为1表示：每个有效地推的注册用户xx元
    //accounttype值为2表示每个有效地推的注册用户xx元，且该用户的每笔消费实付金额满xx以上的订单按xx元／单计为地推订单收入
    //accounttype值为3表示每个有效地推的注册用户xx元，且该用户的每笔消费按实付金额的xx%计为地推订单收入
    //accounttype值为4表示前xx名有效地推用户：每个有效地推的注册用户xx元，且该用户的每笔消费按实付金额的xx%计为地推订单收入；
    //之后的有效地推用户：每个有效地推的注册用户xx元，且该用户的每笔消费按实付金额的xx%计为地推订单收入
    //accounttype值为5表示每个有效地推的注册用户xx元,且该用户首笔金额满多少元以上的充值按xx元／单计为地推充值收入
    //accounttype值为6表示每个有效地推的注册用户xx元,且该用户前xx笔金额满多少元以上的充值按xx元／单计为地推充值收入


    //获取个人地推最新地推设置记录
    public static function getUserLastSalesmanSet($cityId) {
        if(!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $salesmanSet = SalesmanSet::where('cityid', $cityId)->where('salesmantype', 'usersalesman')
            ->where('status', 1)->orderBy('created_at', 'desc')->first();
        if(!$salesmanSet) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $validSalesmanResult = self::getValidSalesmanDefinitionAndAccountMethod($salesmanSet);
        if($validSalesmanResult['status'] == 'success') {
            $showValidSalesman = $validSalesmanResult['data']['showvalidsalesman'];
            $showAccountMethod =$validSalesmanResult['data']['showaccountmethod'];
        } else {
            $showValidSalesman = '';
            $showAccountMethod = '';
        }
        $salesmanSet['showvalidsalesman'] = $showValidSalesman;
        $salesmanSet['showaccountmethod'] = $showAccountMethod;
        return ['status'=>'success', 'data'=>$salesmanSet];
    }
    //根据城市id获取商家地推最新地推设置记录
    public static function getShopLastSalesmanSet($cityId, $shopType='common') {
        if(!$cityId||!$shopType) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $salesmanSet = SalesmanSet::where('cityid', $cityId)->where('salesmantype', 'shopsalesman')->where('shoptype', $shopType)
            ->where('status', 1)->orderBy('created_at', 'desc')->first();
        if(!$salesmanSet) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $validSalesmanResult = self::getValidSalesmanDefinitionAndAccountMethod($salesmanSet);
        if($validSalesmanResult['status'] == 'success') {
            $showValidSalesman = $validSalesmanResult['data']['showvalidsalesman'];
            $showAccountMethod =$validSalesmanResult['data']['showaccountmethod'];
        } else {
            $showValidSalesman = '';
            $showAccountMethod = '';
        }
        $salesmanSet['showvalidsalesman'] = $showValidSalesman;
        $salesmanSet['showaccountmethod'] = $showAccountMethod;
        return ['status'=>'success', 'data'=>$salesmanSet];
    }
    //新增地推记录设置
    public static function addSalesmanSet($data) {
        if(empty($data)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if($data['accounttype'] == 1) {
            $registerGetMoney = $data['registergetmoney1'];
        } elseif($data['accounttype'] == 2) {
            $registerGetMoney = $data['registergetmoney2'];
        } elseif($data['accounttype'] == 3) {
            $registerGetMoney = $data['registergetmoney3'];
        } elseif($data['accounttype'] == 5) {
            $registerGetMoney = $data['registergetmoney5'];
        } elseif($data['accounttype'] == 6) {
            $registerGetMoney = $data['registergetmoney6'];
        } else {
            $registerGetMoney = 0;
        }
        if($data['accounttype'] == 5) {
            $rechargeTopNum = 1;
            $rechargeMinAmount = $data['rechargeminamount5'];
            $rechargeGetMoney = $data['rechargegetmoney5'];
        } elseif($data['accounttype'] == 6) {
            $rechargeTopNum = $data['rechargetopnum6'];
            $rechargeMinAmount = $data['rechargeminamount6'];
            $rechargeGetMoney = $data['rechargegetmoney6'];
        } else {
            $rechargeTopNum = 0;
            $rechargeMinAmount = 0;
            $rechargeGetMoney = 0;
        }

        //新增地推设置
        $addSalesmanSet = SalesmanSet::create([
            'cityid' => $data['cityid'],
            'name' => $data['name'],
            'salesmantype' => $data['salesmantype'],
            'shoptype' => $data['shoptype'],
            'accountperiod' => $data['accountperiod'],
            'accountperioddescription' => $data['accountperioddescription'],
            'validsalesmanruletype' => $data['validsalesmanruletype'],
            'validorderminnum' => $data['validorderminnum'],
            'validorderminamount' => $data['validorderminamount'],
            'accounttype' => $data['accounttype'],
            'registergetmoney' => $registerGetMoney,
            'accountorderminamount' => $data['accountorderminamount'],
            'ordergetmoney' => $data['ordergetmoney'],
            'ordergetratio' => $data['ordergetratio'],
            'topnum' => $data['topnum'],
            'topregistergetmoney' => $data['topregistergetmoney'],
            'topordergetratio' => $data['topordergetratio'],
            'afterregistergetmoney' => $data['afterregistergetmoney'],
            'afterordergetratio' => $data['afterordergetratio'],
            'rechargetopnum' => $rechargeTopNum,
            'rechargeminamount' => $rechargeMinAmount,
            'rechargegetmoney' => $rechargeGetMoney,
            'status' => 1,
            'adminid' => Auth::guard('adminweb')->id(),
        ]);
        $addSalesmanSet->save();
        return ['status'=>'success', 'message'=>'提交成功'];
    }
    //编辑地推记录设置, 这里是一批人，而updateSingleSalesmanSet是单个人
    public static function updateSalesmanSet($data) {
        if(empty($data)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if(!isset($data['cityid']) || !isset($data['salesmansetid']) || !$data['cityid'] || !$data['salesmansetid']) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if($data['accounttype'] == 1) {
            $registerGetMoney = $data['registergetmoney1'];
        } elseif($data['accounttype'] == 2) {
            $registerGetMoney = $data['registergetmoney2'];
        } elseif($data['accounttype'] == 3) {
            $registerGetMoney = $data['registergetmoney3'];
        } elseif($data['accounttype'] == 5) {
            $registerGetMoney = $data['registergetmoney5'];
        } elseif($data['accounttype'] == 6) {
            $registerGetMoney = $data['registergetmoney6'];
        } else {
            $registerGetMoney = 0;
        }
        if($data['accounttype'] == 5) {
            $rechargeTopNum = 1;
            $rechargeMinAmount = $data['rechargeminamount5'];
            $rechargeGetMoney = $data['rechargegetmoney5'];
        } elseif($data['accounttype'] == 6) {
            $rechargeTopNum = $data['rechargetopnum6'];
            $rechargeMinAmount = $data['rechargeminamount6'];
            $rechargeGetMoney = $data['rechargegetmoney6'];
        } else {
            $rechargeTopNum = 0;
            $rechargeMinAmount = 0;
            $rechargeGetMoney = 0;
        }

        //新增地推设置
        $updateData = [
            'name' => $data['name'],
            'salesmantype' => $data['salesmantype'],
            'shoptype' => $data['shoptype'],
            'accountperiod' => $data['accountperiod'],
            'accountperioddescription' => $data['accountperioddescription'],
            'validsalesmanruletype' => $data['validsalesmanruletype'],
            'validorderminnum' => $data['validorderminnum'],
            'validorderminamount' => $data['validorderminamount'],
            'accounttype' => $data['accounttype'],
            'registergetmoney' => $registerGetMoney,
            'accountorderminamount' => $data['accountorderminamount'],
            'ordergetmoney' => $data['ordergetmoney'],
            'ordergetratio' => $data['ordergetratio'],
            'topnum' => $data['topnum'],
            'topregistergetmoney' => $data['topregistergetmoney'],
            'topordergetratio' => $data['topordergetratio'],
            'afterregistergetmoney' => $data['afterregistergetmoney'],
            'afterordergetratio' => $data['afterordergetratio'],
            'rechargetopnum' => $rechargeTopNum,
            'rechargeminamount' => $rechargeMinAmount,
            'rechargegetmoney' => $rechargeGetMoney,
            'status' => 1,
            'adminid' => Auth::guard('adminweb')->id(),
        ];
        SalesmanSet::where('cityid', $data['cityid'])->where('id', $data['salesmansetid'])->update($updateData);
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //获取个人地推设置列表
    public static function userSalesmanSetList($cityId) {
        if(!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = SalesmanSet::where('cityid', $cityId)->where('salesmantype', 'usersalesman')->orderBy('created_at', 'desc')->get();
        foreach($data as $k => $v) {
            $validSalesmanResult = self::getValidSalesmanDefinitionAndAccountMethod($v);
            if($validSalesmanResult['status'] == 'success') {
                $data[$k]['showvalidsalesman'] = $validSalesmanResult['data']['showvalidsalesman'];
                $data[$k]['showaccountmethod'] =$validSalesmanResult['data']['showaccountmethod'];
            } else {
                $data[$k]['showvalidsalesman'] = '';
                $data[$k]['showaccountmethod'] = '';
            }
            $data[$k]['usercount'] = SalesmanInfo::where('cityid', $cityId)->where('salesmansetid', $v->id)->count();
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //获取地推历史设置记录
    public static function historySalesmanSetList($cityId) {
        if(!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = SalesmanSet::where('cityid', $cityId)->orderBy('created_at', 'desc')->get();
        foreach($data as $k => $v) {
            $validSalesmanResult = self::getValidSalesmanDefinitionAndAccountMethod($v);
            if($validSalesmanResult['status'] == 'success') {
                $data[$k]['showvalidsalesman'] = $validSalesmanResult['data']['showvalidsalesman'];
                $data[$k]['showaccountmethod'] =$validSalesmanResult['data']['showaccountmethod'];
            } else {
                $data[$k]['showvalidsalesman'] = '';
                $data[$k]['showaccountmethod'] = '';
            }
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //通过salesmanSetId获取地推设置详情
    public static function getSalesmanSetBySalesmanSetId($cityId, $salesmanSetId) {
        if(!$cityId || !$salesmanSetId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = SalesmanSet::where('cityid', $cityId)->where('id', $salesmanSetId)->first();
        $validSalesmanDefineResult = self::getValidSalesmanDefinitionAndAccountMethod($data);
        if($validSalesmanDefineResult['status'] == 'success') {
            $data['showvalidsalesman'] = $validSalesmanDefineResult['data']['showvalidsalesman'];
            $data['showaccountmethod'] = $validSalesmanDefineResult['data']['showaccountmethod'];
        } else {
            $data['showvalidsalesman'] = '';
            $data['showaccountmethod'] = '';
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //通过salesmanset数据获取有效地推定义和结算方式
    protected static function getValidSalesmanDefinitionAndAccountMethod($data) {
        if(!$data) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $validSalesmanRuleType = $data->validsalesmanruletype;
        $accountType = $data->accounttype;
        if($validSalesmanRuleType == 1) {
            $showValidSalesman = "同城新用户下载翻贝网App，首次登录时扫描地推二维码，获取邀请码完成登录即可。首次登录时未获取邀请码，可在2小时内用扫一扫功能扫地推二维码即可。";
        } elseif($validSalesmanRuleType == 2) {
            $validOrderMinNum = $data->validorderminnum;
            $validOrderMinAmount = $data->validorderminamount;
            $showValidSalesman = "新用户登录app且消费".$validOrderMinNum."笔，单笔消费金额需达".$validOrderMinAmount."以上";
        } else {
            $showValidSalesman = "";
        }
        if($accountType == 1) {
            $registerGetMoney = $data->registergetmoney;
            $showAccountMethod = "每个有效地推的注册用户".$registerGetMoney."元";
        } elseif($accountType == 2) {
            $registerGetMoney = $data->registergetmoney;
            $accountOrderMinAmount = $data->accountorderminamount;
            $orderGetMoney = $data->ordergetmoney;
            $showAccountMethod = "每个有效地推的注册用户".$registerGetMoney."元，且该用户的每笔消费实付金额满".$accountOrderMinAmount."以上的订单按".$orderGetMoney."元／单计为地推订单收入";
        } elseif($accountType == 3) {
            $registerGetMoney = $data->registergetmoney;
            $orderGetRatio = $data->ordergetratio;
            $showAccountMethod = "每个有效地推的注册用户".$registerGetMoney."元，且该用户的每笔消费按实付金额的".$orderGetRatio."%计为地推订单收入";
        } elseif($accountType == 4) {
            $topNum = $data->topnum;
            $topRegisterGetMoney = $data->topregistergetmoney;
            $topOrderGetRatio = $data->topordergetratio;
            $afterRegisterGetMoney = $data->afterregistergetmoney;
            $afterOrderGetRatio = $data->afterordergetratio;
            $showAccountMethod = "前".$topNum."名有效地推用户：每个有效地推的注册用户".$topRegisterGetMoney."元，且该用户的每笔消费按实付金额的".$topOrderGetRatio."%计为地推订单收入" .
                "之后的有效地推用户：每个有效地推的注册用户".$afterRegisterGetMoney."元，且该用户的每笔消费按实付金额的".$afterOrderGetRatio."%计为地推订单收入";
        } elseif($accountType == 5) {
            $registerGetMoney = $data->registergetmoney;
            $rechargeMinAmount = $data->rechargeminamount;
            $rechargeGetMoney = $data->rechargegetmoney;
            $showAccountMethod = "每个有效地推的注册用户".$registerGetMoney."元,且该用户首笔金额满".$rechargeMinAmount."元以上的充值按".$rechargeGetMoney."元／单计为地推充值收入";
        } elseif($accountType == 6) {
            $registerGetMoney = $data->registergetmoney;
            $rechargeTopNum = $data->rechargetopnum;
            $rechargeMinAmount = $data->rechargeminamount;
            $rechargeGetMoney = $data->rechargegetmoney;
            $showAccountMethod = "每个有效地推的注册用户".$registerGetMoney."元,且该用户前".$rechargeTopNum."笔金额满".$rechargeMinAmount."元以上的充值按".$rechargeGetMoney."元／单计为地推充值收入";
        } else {
            $showAccountMethod = "";
        }
        $returnData = [
            'showvalidsalesman' => $showValidSalesman,
            'showaccountmethod' => $showAccountMethod,
        ];
        return ['status'=>'success', 'data'=>$returnData];
    }
    //个人地推列表
    public static function userSalesmanList($cityId,$search='') {
        if(!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if($search) {
            $GLOBALS['search'] = $search;
            $total = SalesmanInfo::where('salesman_info.cityid', $cityId)
                ->join('users', 'salesman_info.salesmanid', '=', 'users.id')
                ->where(function($query) {
                    $query->orwhere('users.mobile', $GLOBALS['search'])->orwhere('users.nickname', 'like', '%'.$GLOBALS['search'].'%')->orwhere('salesman_info.qrcode', $GLOBALS['search']);
                })->count();
            $registerCount = SalesmanInfo::where('salesman_info.cityid', $cityId)
                ->join('users', 'salesman_info.salesmanid', '=', 'users.id')
                ->where(function($query) {
                    $query->orwhere('users.mobile', $GLOBALS['search'])->orwhere('users.nickname', 'like', '%'.$GLOBALS['search'].'%')->orwhere('salesman_info.qrcode', $GLOBALS['search']);
                })->sum('salesman_info.registernum');
            $orderCount = SalesmanInfo::where('salesman_info.cityid', $cityId)
                ->join('users', 'salesman_info.salesmanid', '=', 'users.id')
                ->where(function($query) {
                    $query->orwhere('users.mobile', $GLOBALS['search'])->orwhere('users.nickname', 'like', '%'.$GLOBALS['search'].'%')->orwhere('salesman_info.qrcode', $GLOBALS['search']);
                })->sum('salesman_info.ordernum');
            $orderValidCount = SalesmanInfo::where('salesman_info.cityid', $cityId)
                ->join('users', 'salesman_info.salesmanid', '=', 'users.id')
                ->where(function($query) {
                    $query->orwhere('users.mobile', $GLOBALS['search'])->orwhere('users.nickname', 'like', '%'.$GLOBALS['search'].'%')->orwhere('salesman_info.qrcode', $GLOBALS['search']);
                })->sum('salesman_info.ordervalidnum');
            $rechargeCount = SalesmanInfo::where('salesman_info.cityid', $cityId)
                ->join('users', 'salesman_info.salesmanid', '=', 'users.id')
                ->where(function($query) {
                    $query->orwhere('users.mobile', $GLOBALS['search'])->orwhere('users.nickname', 'like', '%'.$GLOBALS['search'].'%')->orwhere('salesman_info.qrcode', $GLOBALS['search']);
                })->sum('salesman_info.rechargenum');
            $orderTotalAmount = SalesmanInfo::where('salesman_info.cityid', $cityId)
                ->join('users', 'salesman_info.salesmanid', '=', 'users.id')
                ->where(function($query) {
                    $query->orwhere('users.mobile', $GLOBALS['search'])->orwhere('users.nickname', 'like', '%'.$GLOBALS['search'].'%')->orwhere('salesman_info.qrcode', $GLOBALS['search']);
                })->sum('salesman_info.ordertotalamount');
            $totalGetMoney = SalesmanInfo::where('salesman_info.cityid', $cityId)
                ->join('users', 'salesman_info.salesmanid', '=', 'users.id')
                ->where(function($query) {
                    $query->orwhere('users.mobile', $GLOBALS['search'])->orwhere('users.nickname', 'like', '%'.$GLOBALS['search'].'%')->orwhere('salesman_info.qrcode', $GLOBALS['search']);
                })->sum('salesman_info.totalmoney');
            $userList = SalesmanInfo::where('salesman_info.cityid', $cityId)
                ->join('users', 'salesman_info.salesmanid', '=', 'users.id')
                ->where(function($query) {
                    $query->orwhere('users.mobile', $GLOBALS['search'])->orwhere('users.nickname', 'like', '%'.$GLOBALS['search'].'%')->orwhere('salesman_info.qrcode', $GLOBALS['search']);
                })->select('salesman_info.*', 'users.mobile as mobile')->get();
        } else {
            $total = SalesmanInfo::where('cityid', $cityId)->count();
            $registerCount = SalesmanInfo::where('cityid', $cityId)->sum('registernum');
            $orderCount = SalesmanInfo::where('cityid', $cityId)->sum('ordernum');
            $orderValidCount = SalesmanInfo::where('cityid', $cityId)->sum('ordervalidnum');
            $rechargeCount = SalesmanInfo::where('cityid', $cityId)->sum('rechargenum');
            $orderTotalAmount = SalesmanInfo::where('cityid', $cityId)->sum('ordertotalamount');
            $totalGetMoney = SalesmanInfo::where('cityid', $cityId)->sum('totalmoney');
            $userList = SalesmanInfo::where('salesman_info.cityid', $cityId)
                ->join('users', 'salesman_info.salesmanid', '=', 'users.id')
                ->select('salesman_info.*', 'users.mobile as mobile')->get();
        }
        $data = [
            'cityid' => $cityId,
            'search' => $search,
            'total' => $total,
            'registercount' => $registerCount,
            'ordercount' => $orderCount,
            'ordervalidcount' => $orderValidCount,
            'ordertotalamount' => $orderTotalAmount,
            'rechargecount' => $rechargeCount,
            'totalgetmoney' => $totalGetMoney,
            'userlist' => $userList
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //通过cityid和salesmansetid获取个人地推列表
    public static function getUserSalesmanListByCityIdAndSalesmanSetId($cityId, $salesmanSetId) {
        if(!$cityId||!$salesmanSetId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = SalesmanInfo::where('salesman_info.cityid', $cityId)
            ->where('salesman_info.salesmansetid', $salesmanSetId)
            ->join('users', 'salesman_info.salesmanid', '=', 'users.id')
            ->orderBy('salesman_info.created_at', 'desc')
            ->select('salesman_info.created_at', 'salesman_info.salesmanid','salesman_info.name', 'users.mobile', 'salesman_info.qrcode', 'salesman_info.registernum',
                'salesman_info.totalmoney', 'salesman_info.status')
            ->get();
        return ['status'=>'success', 'data'=>$data];
    }
    //获取个人地推方案中的ids和名称
    public static function getUserSalesmanSetIdsAndNames($cityId) {
        if(!$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = SalesmanSet::where('cityid', $cityId)->select('id as salesmansetid', 'name')->get();
        return ['status'=>'success', 'data'=>$data];
    }
    //新增个人地推
    public static function addUserSalesman($userName, $mobile, $ciyId, $salesmanSetId, $remark='') {
        if(!$userName|| !$mobile || !$ciyId || !$salesmanSetId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $user = User::where('mobile', $mobile)->first();
        if(!$user) {
            return ['status'=>'failed', 'message'=>'该手机号码还没有注册'];
        }
        if($user->issalesman == 1) {
            return ['status'=>'failed', 'message'=>'该手机已是地推用户'];
        }
        $salesmanInfo = SalesmanInfo::create([
            'salesmanid' => $user->id,
            'cityid' => $ciyId,
            'name' => $userName,
            'salesmansetid' => $salesmanSetId,
            'effectivedate' => date('Y-m-d') . " 00:00:00",
            'status' => 1,
            'adminid' => Auth::guard('adminweb')->id(),
            'info' => $remark
        ]);
        $salesmanInfo->save();
        $user->issalesman = 1;
        $user->save();
        return ['status'=>'success', 'message'=>'创建成功'];
    }
    //个人地推详情
    public static function getUserSalesmanDetail($salesmanId) {
        if(!$salesmanId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = SalesmanInfo::where('salesman_info.salesmanid', $salesmanId)
            ->join('users', 'salesman_info.salesmanid', '=', 'users.id')
            ->join('city', 'salesman_info.cityid', '=', 'city.id')
            ->select('salesman_info.*', 'users.nickname', 'users.mobile', 'users.registerarea', 'users.issalesman', 'city.name as cityname')
            ->first();
        if(!$data) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $salesmanSetDetailResult = self::getSalesmanSetBySalesmanSetId($data['cityid'], $data['salesmansetid']);
        if($salesmanSetDetailResult['status'] == 'failed') {
            $data['salesmansetdetail'] = [];
        } else {
            $data['salesmansetdetail'] = $salesmanSetDetailResult['data'];
        }
        $data['lastsalesmansetdetail'] = [];
        if($data['lastsalesmansetid']) {
            $lastSalesmanSetDetailResult = self::getSalesmanSetBySalesmanSetId($data['cityid'], $data['lastsalesmansetid']);
            if($lastSalesmanSetDetailResult['status'] == 'success') {
                $data['lastsalesmansetdetail'] = $lastSalesmanSetDetailResult['data'];
                $history = SalesmanHistory::where('salesmanid', $salesmanId)->where('salesmansetid', $data['lastsalesmansetid'])
                    ->select('registernum', 'ordernum', 'ordertotalamount', 'rechargenum', 'totalmoney')->first();
                if($history) {
                    $data['lastsalesmansetdetail']['currentregisternum'] = $history['registernum'];
                    $data['lastsalesmansetdetail']['currentordernum'] = $history['ordernum'];
                    $data['lastsalesmansetdetail']['currentordertotalamount'] = $history['ordertotalamount'];
                    $data['lastsalesmansetdetail']['currentrechargenum'] = $history['rechargenum'];
                    $data['lastsalesmansetdetail']['currenttotalmoney'] = $history['totalmoney'];
                } else {
                    $data['lastsalesmansetdetail']['currentregisternum'] = 0;
                    $data['lastsalesmansetdetail']['currentordernum'] = 0;
                    $data['lastsalesmansetdetail']['currentordertotalamount'] = 0.00;
                    $data['lastsalesmansetdetail']['currentrechargenum'] = 0;
                    $data['lastsalesmansetdetail']['currenttotalmoney'] = 0.00;
                }
            }
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //个人地推详情中获取注册用户和地推订单
    public static function getUserSalesmanDetailByType($salesmanId, $salesmanSetId, $type, $page=1, $length=20) {
        if(!$salesmanId||!$type || !$salesmanSetId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $salesmanInfo = SalesmanInfo::where('salesmanid', $salesmanId)->first();
        if(!$salesmanInfo) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $isSalesmanHistory = SalesmanHistory::where('salesmanid', $salesmanId)->first();
        if(!$isSalesmanHistory) {
            //没有修改过地推规则
            $lastTime = date('Y-m-d H:i:s');
            $startTime = '2017-03-01 00:00:00';
        } else {
            //修改过地推规则
            $newSalesmanHistory = SalesmanHistory::where('salesmanid', $salesmanId)->where('salesmansetid', $salesmanSetId)->first();
            if($newSalesmanHistory) {
                $salesmanHistoryId = $newSalesmanHistory->id;
                $lastTime = date('Y-m-d H:i:s', strtotime($newSalesmanHistory->created_at));
            } else {
                $salesmanHistoryId = 0;
                $lastTime = date('Y-m-d H:i:s');
            }
            if($salesmanHistoryId) {
                $oldSalesmanHistory = SalesmanHistory::where('salesmanid', $salesmanId)->where('id', '<', $salesmanHistoryId)->orderBy('created_at', 'desc')->first();
            } else {
                $oldSalesmanHistory = SalesmanHistory::where('salesmanid', $salesmanId)->orderBy('created_at', 'desc')->first();
            }
            if($oldSalesmanHistory) {
                $startTime =  date('Y-m-d H:i:s', strtotime($oldSalesmanHistory->created_at));
            }else {
                $startTime = '2017-03-01 00:00:00';
            }
        }
        $skip = ($page-1)*$length;
        if($type == 'register') {
            $total = SalesmanRegister::where('salesmanid', $salesmanId)->where('created_at', '>=', $startTime)->where('created_at', '<', $lastTime)->count();
            $lists = SalesmanRegister::where('salesman_register.salesmanid', $salesmanId)
                ->where('salesman_register.created_at', '>=', $startTime)->where('salesman_register.created_at', '<', $lastTime)
                ->join('users', 'salesman_register.registermobile', '=', 'users.mobile')
                ->orderBy('salesman_register.created_at', 'desc')
                ->select('salesman_register.created_at', 'salesman_register.registermobile', 'salesman_register.id as salesmanregisterid','users.id as userid')
                ->skip($skip)->take($length)->get();
            foreach($lists as $k => $v) {
                $lists[$k]['registermobile'] = str_replace(substr($lists[$k]['registermobile'], 3, 4), '****', $lists[$k]['registermobile']);
                $lists[$k]['ordernum'] = SalesmanOrder::where('registerid', $lists[$k]['userid'])->where('created_at', '>=', $startTime)->where('created_at', '<', $lastTime)->count();
                $lists[$k]['ordervalidnum'] = SalesmanOrder::where('registerid', $lists[$k]['userid'])->where('created_at', '>=', $startTime)->where('created_at', '<', $lastTime)->where('isvalid',1)->count();
                $orderAmount = SalesmanOrder::where('registerid', $lists[$k]['userid'])->sum('orderamount');
                $lists[$k]['orderamount'] = ($orderAmount == '')? 0 : $orderAmount;
            }
        } elseif($type == 'order') {
            $total = SalesmanOrder::where('salesmanid', $salesmanId)->where('created_at', '>=', $startTime)->where('created_at', '<', $lastTime)->count();
            $lists = SalesmanOrder::where('salesman_order.salesmanid', $salesmanId)
                ->where('salesman_order.created_at', '>=', $startTime)->where('salesman_order.created_at', '<', $lastTime)
                ->join('orders', 'salesman_order.orderid', '=', 'orders.id')
                ->join('shops', 'orders.shopid', '=', 'shops.id')
                ->orderBy('salesman_order.created_at', 'desc')
                ->select('salesman_order.created_at', 'orders.ordernumber', 'salesman_order.registermobile', 'salesman_order.registerid as userid','shops.name as shopname',
                    'shops.code as shopcode', 'salesman_order.orderamount')
                ->skip($skip)->take($length)->get();
            foreach($lists as $k => $v) {
                $lists[$k]['registermobile'] = str_replace(substr($lists[$k]['registermobile'], 3, 4), '****', $lists[$k]['registermobile']);
            }
        } elseif($type == 'recharge') {
            $total = SalesmanRecharge::where('salesmanid', $salesmanId)->where('created_at', '>=', $startTime)->where('created_at', '<', $lastTime)->count();
            $lists = SalesmanRecharge::where('salesmanid', $salesmanId)
                ->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)
                ->orderBy('created_at', 'desc')
                ->select('created_at', 'rechargenumber', 'registermobile',  'rechargeamount')
                ->skip($skip)->take($length)->get();
            foreach($lists as $k => $v) {
                $lists[$k]['registermobile'] = str_replace(substr($lists[$k]['registermobile'], 3, 4), '****', $lists[$k]['registermobile']);
            }
        } else {
            $total = 0;
            $lists = [];
        }
        $data = [
            'starttime' => $startTime,
            'lasttime' => $lastTime,
            'total' => $total,
            'lists' => $lists
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //修改个人地推的地推状态
    public static function updateUserSalesmanStatus($salesmanId, $status) {
        if(!$salesmanId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $updateUserSalesmanInfo = SalesmanInfo::where('salesmanid', $salesmanId)->update(['status'=>$status]);
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //修改单个个人地推设置，仅仅是一个人，不同于updateUserSalesmanSet
    public static function updateSingleUserSalesmanSet($salesmanId, $salesmanSetId) {
        if(!$salesmanId||!$salesmanSetId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $salesmanInfo = SalesmanInfo::where('salesmanid', $salesmanId)->first();
        if(!$salesmanInfo) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        if($salesmanInfo->salesmansetid == $salesmanSetId) {
            return ['status'=>'failed', 'message'=>'与原地推方案一样'];
        }
        $oldSalesmanSetId = $salesmanInfo->salesmansetid;
        //将数据salesman_info中的currentregisternum，currentordernum，currentordertotalamount，currentrechargenum，currenttotalmoney清零
        //生成一条待提现记录salesman_withdraw
        $salesmanSet = SalesmanSet::where('id', $oldSalesmanSetId)->first();
        if(!$salesmanSet) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $salesmanSetAccountType = $salesmanSet->accounttype;
        //accounttype值为1表示：每个有效地推的注册用户xx元
        //accounttype值为2表示每个有效地推的注册用户xx元，且该用户的每笔消费实付金额满xx以上的订单按xx元／单计为地推订单收入
        //accounttype值为3表示每个有效地推的注册用户xx元，且该用户的每笔消费按实付金额的xx%计为地推订单收入
        //accounttype值为4表示前xx名有效地推用户：每个有效地推的注册用户xx元，且该用户的每笔消费按实付金额的xx%计为地推订单收入；
        //之后的有效地推用户：每个有效地推的注册用户xx元，且该用户的每笔消费按实付金额的xx%计为地推订单收入
        //accounttype值为5表示每个有效地推的注册用户xx元,且该用户首笔金额满多少元以上的充值按xx元／单计为地推充值收入
        //accounttype值为6表示每个有效地推的注册用户xx元,且该用户前xx笔金额满多少元以上的充值按xx元／单计为地推充值收入
        $currentRegisterNum = $salesmanInfo->currentregisternum;
        $currentOrderNum = $salesmanInfo->currentordernum;
        $currentOrderTotalAmount = $salesmanInfo->currentordertotalamount;
        $currentRechargeNum = $salesmanInfo->currentrechargenum;
        $currentRechargeTotalAmount = $salesmanInfo->currentrechargetotalamount;
        if($salesmanSetAccountType == 1) {
            $registerGetMoney = $salesmanSet->registergetmoney;
            $getMoney = $currentRegisterNum * $registerGetMoney;
        } elseif($salesmanSetAccountType == 2) {
            $registerGetMoney = $salesmanSet->registergetmoney;
            $orderGetMoney = $salesmanSet->ordergetmoney;
            $getMoney = $currentRegisterNum * $registerGetMoney + $orderGetMoney * $currentOrderNum;
        } elseif($salesmanSetAccountType == 3) {
            $registerGetMoney = $salesmanSet->registergetmoney;
            $orderGetRatio = $salesmanSet->ordergetratio;
            $getMoney = $registerGetMoney * $currentRegisterNum + round($orderGetRatio * $currentOrderTotalAmount /100, 2);
        } elseif($salesmanSetAccountType == 4) {
            $topNum = $salesmanSet->topnum;
            $topRegisterGetMoney = $salesmanSet->topregistergetmoney;
            $topOrderGetRatio = $salesmanSet->topordergetratio;
            $afterRegisterGetMoney = $salesmanSet->afterregistergetmoney;
            $afterOrderGetRatio = $salesmanSet->afterordergetratio;
            if($currentRegisterNum <= $topNum) {
                $getMoney = $currentRegisterNum * $topRegisterGetMoney + round($currentOrderTotalAmount*$topOrderGetRatio/100, 2);
            } else {
                $getMoney = $currentRegisterNum * $afterRegisterGetMoney + round($currentOrderTotalAmount*$topOrderGetRatio/100, 2);//TODO有bug
            }
        } elseif($salesmanSetAccountType == 5 || $salesmanSetAccountType == 6) {
            $registerGetMoney = $salesmanSet->registergetmoney;
            $rechargeGetMoney = $salesmanSet->rechargegetmoney;
            $getMoney = $registerGetMoney * $currentRegisterNum + $currentRechargeNum * $rechargeGetMoney;
        } else {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $salesmanWithdraw = SalesmanWithdraw::create([
            'salesmanid' => $salesmanId,
            'accountmoney' => $getMoney,
            'accounttime' => date('Y-m-d H:i:s'),
            'accountmonth' => date('Y-m-d'),
            'registernum' => $currentRegisterNum,
            'ordernum' => $currentOrderNum,
            'ordertotalamount' => $currentOrderTotalAmount,
            'rechargenum' => $currentRechargeNum,
            'rechargetotalamount' => $currentRechargeTotalAmount,
            'status' => 0,
            'adminid' => $salesmanInfo->adminid,
        ]);
        $salesmanWithdraw->save();
        //将数据写入到salesman_history，
        $salesmanHistory = SalesmanHistory::create([
            'salesmanid' =>  $salesmanId,
            'cityid' => $salesmanInfo->cityid,
            'name' => $salesmanInfo->name,
            'registernum' => $salesmanInfo->currentregisternum,
            'ordernum' => $salesmanInfo->currentordernum,
            'ordertotalamount' => $salesmanInfo->currentordertotalamount,
            'rechargenum' => $salesmanInfo->currentrechargenum,
            'rechargetotalamount' => $salesmanInfo->currentrechargetotalamount,
            'totalmoney' => $salesmanInfo->currenttotalmoney,
            'salesmansetid' => $oldSalesmanSetId,
            'adminid' => $salesmanInfo->adminid
        ]);
        $salesmanHistory->save();
        //将salesman_info中的effectivedate生效时间改成明天，修改salesmansetid，lastsalesmansetid
        $salesmanInfo->lastsalesmansetid = $oldSalesmanSetId;
        $salesmanInfo->salesmansetid = $salesmanSetId;
        $salesmanInfo->effectivedate = date('Y-m-d H:i:s');
        $salesmanInfo->adminid = Auth::guard('adminweb')->id();
        $salesmanInfo->currentregisternum = 0;
        $salesmanInfo->currentordernum = 0;
        $salesmanInfo->currentordertotalamount = 0.00;
        $salesmanInfo->currentrechargenum = 0;
        $salesmanInfo->currentrechargetotalamount = 0.00;
        $salesmanInfo->currenttotalmoney = 0.00;
        $salesmanInfo->save();
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //获取某个人的地推订单
    public static function personSalesmanOrderLists($userId, $page=1, $length=10) {
        if(!$userId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $skip = ($page-1)*$length;
        $salesmanId = User::where('id', $userId)->pluck('salesmanid')->first();
        $mobile = User::where('id', $salesmanId)->pluck('mobile')->first();
        $name = SalesmanInfo::where('salesmanid', $salesmanId)->pluck('name')->first();
        $count = SalesmanOrder::where('registerid', $userId)->get()->count();
        $lists = SalesmanOrder::where('salesman_order.registerid', $userId)
            ->join('orders', 'salesman_order.orderid', '=', 'orders.id')
            ->select('orders.created_at', 'orders.ordernumber', 'orders.orderamount')
            ->skip($skip)->take($length)->get();
        $data = [
            'mobile' => $mobile,
            'name' => $name,
            'count' => $count,
            'lists' => $lists
        ];
        return ['status'=>'success', 'data'=>$data];
    }
}